//
//  LSYParseModel.m
//  LSYReader
//
//  Created by sam on 2018/3/22.
//  Copyright © 2018年 okwei. All rights reserved.
//
#import "JSONKit.h"
#import "LSYNetUtil.h"
#import "LSYParseModel.h"

#import "NSArray+EV.h"
#import "NSString+EV.h"
#import "NSString+HTML.h"
#import "NSDictionary+EV.h"

@implementation LSYParseModel

- (instancetype)initWithDiction:(NSDictionary *)dict {
    if (self = [super init]) {
        self.bookAuthor = [dict ev_stringObjectForKey:@"bookAuthor"];
        self.bookCategory = [dict ev_stringObjectForKey:@"bookCategory"];
        self.bookDesc = [dict ev_stringObjectForKey:@"bookDesc"];
        self.bookIcon = [dict ev_stringObjectForKey:@"bookIcon"];
        self.bookLastChapterName = [dict ev_stringObjectForKey:@"bookLastChapterName"];
        self.bookName = [dict ev_stringObjectForKey:@"bookName"];
        self.bookUpdateTime = [dict ev_stringObjectForKey:@"bookUpdateTime"];
        self.bookUrl = [dict ev_stringObjectForKey:@"bookUrl"];
        
        self.books = [dict ev_stringObjectForKey:@"books"];
        self.chapterName = [dict ev_stringObjectForKey:@"chapterName"];
        self.chapterUrl = [dict ev_stringObjectForKey:@"chapterUrl"];
        self.chapters = [dict ev_stringObjectForKey:@"chapters"];
        self.checked = [dict ev_boolForKey:@"checked"];
        self.content = [dict ev_stringObjectForKey:@"content"];
        self.contentReplace = [dict ev_stringObjectForKey:@"contentReplace"];
        self.contentRemove = [dict ev_stringObjectForKey:@"contentRemove"];
        self.enabled = [dict ev_boolForKey:@"enabled"];
        
        self.encoding = [dict ev_stringObjectForKey:@"encoding"];
        self.host = [dict ev_stringObjectForKey:@"host"];
        self.indexUrl = [dict ev_stringObjectForKey:@"indexUrl"];
        self.name = [dict ev_stringObjectForKey:@"name"];
        self.order = [dict ev_integerForKey:@"order"];
        self.searchEncoding = [dict ev_stringObjectForKey:@"searchEncoding"];
        self.searchMore = [dict ev_stringObjectForKey:@"searchMore"];
        self.searchMoreHref = [dict ev_stringObjectForKey:@"searchMoreHref"];
        self.searchUrl = [dict ev_stringObjectForKey:@"searchUrl"];
        self.searchToDetail = [dict ev_boolForKey:@"searchToDetail" withDefault:NO];
        self.detailBookIcon = [dict ev_stringObjectForKey:@"detailBookIcon"];
        self.detailChaptersUrl = [dict ev_stringObjectForKey:@"detailChaptersUrl"];
        
        self.type = [dict ev_integerForKey:@"type"];
    }
    return self;
}

- (NSArray *)contentReplaces {
    NSArray *replaces = [self.contentReplace objectFromJSONString];
    return replaces;
}

- (NSArray *)contentRemoves {
    return [self.contentRemove objectFromJSONString];
}

- (NSString *)searchUrl {
    return [_searchUrl stringByReplacingOccurrencesOfString:@"%s" withString:@"%@"];
}

- (NSString *)getElText:(HTMLNode *)el rule:(NSString *)rule relativeUrl:(NSURL *)url {
    return [self getElText:el rule:rule relativeUrl:url isHtml:NO];
}

- (NSString *)getElText:(HTMLNode *)el rule:(NSString *)rule relativeUrl:(NSURL *)url isHtml:(BOOL)isHtml {
    if (el==nil) {
        return @"";
    }
    if (rule.length==0) {
        return @"--";
    }
    NSArray *rules = [self parseRule:rule];
    if (rules.count ==0) {
        return el.textContent.ev_trim;
    }
    if (rules.count >=3) {
        NSString *selStr = [rules firstObject];
        if (selStr.length>0) {
            NSInteger index = [[rules ev_safeObjectAtIndex:1] integerValue];
            NSArray *els = [el querySelectorAll:selStr];
            if (els.count<index) {
                return @"";
            }
            HTMLElement *targetEl = [els ev_safeObjectAtIndex:index];
            return [self getAttrText:targetEl attr:[rules ev_safeObjectAtIndex:2] relativeUrl:url isHTML:isHtml];
        }else {
            //handle the third params
            return [self getAttrText:el attr:[rules ev_safeObjectAtIndex:2] relativeUrl:url isHTML:isHtml];
        }
    }
    return @"";
}


- (NSString *)getAttrText:(HTMLNode *)el attr:(NSString *)attr relativeUrl:(NSURL *)relUrl isHTML:(BOOL)isHTML {
    if (el==nil) {
        return @"";
    }
    if (attr.length<=0) {
        if (isHTML) {
            return el.innerHTML;
        } else {
            return el.textContent.ev_trim;
        }
    }
    NSInteger index = [attr rangeOfString:@":"].location;
    if (index == NSNotFound) {
        return [[(HTMLElement*)el attributes] ev_stringObjectForKey:attr].ev_trim;
    } else {
        NSString *rule = [attr substringToIndex:index];
        NSString *realAttr = [attr substringFromIndex:(index+1)];
        if ([rule isEqualToString:@"abs"]) {
            NSString *url = [[(HTMLElement*)el attributes] ev_stringObjectForKey:realAttr];
            return [NSURL URLWithString:url relativeToURL:relUrl].absoluteString;
        } else if ([rule isEqualToString:@"own"]) {
            if (realAttr.length>0) {
                return [[LSYNetUtil ownerText:el] ev_stringByMatching:realAttr capture:1];
            }
            return [LSYNetUtil ownerText:el];
        } else {
            NSString *content = @"";
            if (isHTML) {
                content = el.innerHTML;
            } else {
                content = el.textContent.ev_trim;
            }
            return [content ev_stringByMatching:realAttr capture:1];
        }
    }
}

- (NSArray *)parseRule:(NSString *)rule {
    // get text
    if ([rule isEqualToString:@"@@@"]) {
        return [NSArray array];
    }
    if ([rule hasPrefix:@"@"]) {
        NSArray *components = [rule componentsSeparatedByString:@"@"];
        NSMutableArray *mutArray = [NSMutableArray arrayWithArray:components];
        [mutArray removeObjectAtIndex:0];
        return mutArray;
    } else {
        //get content with rule
        return nil;
    }
}
@end
